package org.jeecg.modules.mes.storage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.epms.util.ObjectHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataMateriel;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataProductline;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.chiefdata.entity.MesPrintModel;
import org.jeecg.modules.mes.client.ProduceClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.*;
import org.jeecg.modules.mes.organize.entity.MesShelfUtil;
import org.jeecg.modules.mes.print.conHead;
import org.jeecg.modules.mes.print.conmap;
import org.jeecg.modules.mes.print.mesUtil;
import org.jeecg.modules.mes.produce.entity.MesAncillarytoolStir;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltable;
import org.jeecg.modules.mes.storage.entity.*;
import org.jeecg.modules.mes.storage.service.*;
import org.jeecg.modules.mes.storage.utils.AsyncUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: 仓库管理—批号交易
 * @Author: jeecg-boot
 * @Date: 2020-09-14
 * @Version: V1.0
 */
@Api(tags = "仓库管理—批号交易")
@RestController
@RequestMapping("/storage/mesStorageWholesale")
@Slf4j
@Scope(value = "prototype")//多例模式
public class MesStorageWholesaleController extends JeecgController<MesStorageWholesale, IMesStorageWholesaleService> {
    @Autowired
    private IMesStorageWholesaleService mesStorageWholesaleService;

    @Autowired
    private IMesStockManageService mesStockManageService;

    @Autowired
    private IMesWarehouseAreaService mesWarehouseAreaService;

    @Autowired
    private IMesCertificatePerkService mesCertificatePerkService;

    @Autowired
    private IMesCertificateItemService mesCertificateItemService;

    @Autowired
    private IMesMaterielOccupyService mesMaterielOccupyService;

    @Autowired
    private IMesShelfIpConfigService mesShelfIpConfigService;

    @Autowired
    private IMesErrorOperationRecordService iMesErrorOperationRecordService;

    @Autowired
    private IMesWarehouseAreaService iMesWarehouseAreaService;

    @Autowired
    SystemClient systemClient;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TransactionClient transactionClient;

    @Autowired
    ProduceClient produceClient;

    @Autowired
    private AsyncUtils asyncUtils;


    private ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * 分页列表查询
     *
     * @param mesStorageWholesale
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-分页列表查询")
    @ApiOperation(value = "仓库管理—批号交易-分页列表查询", notes = "仓库管理—批号交易-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesStorageWholesale mesStorageWholesale,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesStorageWholesale> queryWrapper = QueryGenerator.initQueryWrapper(mesStorageWholesale, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<MesStorageWholesale> page = new Page<MesStorageWholesale>(pageNo, pageSize);
        IPage<MesStorageWholesale> pageList = mesStorageWholesaleService.page(page, queryWrapper);
        return Result.ok(pageList);
    }


    /**
     * 调用智能货架，自己封装的实体类
     *
     * @param shelfDataList
     * @return
     */
    public static MesShelfLight ShelfLight(List<MesShelfData> shelfDataList) {
        MesShelfLight mesShelfLight = new MesShelfLight();
        mesShelfLight.setControl_caty("A3");//第三排货架
        mesShelfLight.setApp_id(12345678);//固定值，无特殊意义
        List<MesShelfData> data = new ArrayList<>();
        data.addAll(shelfDataList);
        mesShelfLight.setData(data);
        return mesShelfLight;
    }
    /**
     * 查询该采购子表id的收货数量
     * @param purchaseItemId
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-查询采购订单子表id的收货数量")
    @ApiOperation(value = "仓库管理—批号交易-查询采购订单子表id的收货数量", notes = "仓库管理—批号交易-查询采购订单子表id的收货数量")
    @GetMapping(value = "/queryPurchaseItemSum")
    public int queryPurchaseItemSum(@RequestParam(name = "purchaseItemId", required = true)String purchaseItemId){
        return mesStorageWholesaleService.queryPurchaseItemSum(purchaseItemId);
    }


    /**
     * 打印了还未收货的数量
     * @param purchaseItemId 采购订单子表id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-查询采购订单子表id的打印了还未收货的数量")
    @ApiOperation(value = "仓库管理—批号交易-查询采购订单子表id的打印了还未收货的数量", notes = "仓库管理—批号交易-查询采购订单子表id的打印了还未收货的数量")
    @GetMapping(value = "/queryPrintUnreceiveNum")
    public int queryPrintUnreceiveNum(@RequestParam(name = "purchaseItemId", required = true)String purchaseItemId){
        return mesStorageWholesaleService.queryPrintUnreceiveNum(purchaseItemId);
    }
    /**
     * 智能货架的亮灯测试
     *
     * @param start
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-货架灯测试")
    @ApiOperation(value = "仓库管理—批号交易-货架灯测试", notes = "仓库管理—批号交易-货架灯测试")
    @GetMapping(value = "/shelfLightTest")
    public Result<?> shelfLightTest(@RequestParam(name = "start", required = false) String start) {
        List<MesShelfData> shelfDataList = new ArrayList<>();
        int j = 0;
        for (int i = 0; i < 3; i++) {
            j += 1;
            MesShelfData mesShelfData = new MesShelfData();
            mesShelfData.setCell_num("003-000" + j + "");
            mesShelfData.setIndex(1);
            mesShelfData.setColor("black");
            mesShelfData.setBlink(0);
            shelfDataList.add(mesShelfData);
        }
        MesShelfLight mesShelfLight = ShelfLight(shelfDataList);
        String url = "http://192.168.10.13:9999/RecvInterface";
        String test = MesShelfUtil.litShelfLight(url, mesShelfLight);
        return Result.ok(test);
    }


    /**
     * 通过料号与颜色，智能货架上该物料所在的位置，亮起相应颜色的灯
     *
     * @param mCode 料号
     * @param color 颜色
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-发料亮灯")
    @ApiOperation(value = "仓库管理—批号交易-发料亮灯", notes = "仓库管理—批号交易-发料亮灯")
    @GetMapping(value = "/sendLitLight")
    public Result<?> sendLitLight(@RequestParam(name = "mCode", required = false) String mCode,
                                  @RequestParam(name = "color", required = false) String color) {
        QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_code", mCode).eq("base_dockettype", "收货打印").eq("shelf_state", "0");
        List<MesStorageWholesale> wholesaleList = mesStorageWholesaleService.list(queryWrapper);
        Map<String, List<MesShelfData>> map = new HashMap<>();
        if (wholesaleList.size() != 0) {
            for (MesStorageWholesale wholesale : wholesaleList) {
                String shelfCode = wholesale.getShelfCode();//货架编码
                //根据前缀查询货架编号
                MesShelfIpConfig mesShelfIpConfig =
                        mesShelfIpConfigService.lambdaQuery().eq(MesShelfIpConfig::getShelfCodePre, shelfCode.split("-")[0]).one();
                if (mesShelfIpConfig == null) {
                    Result.error("货架没有配置Host");
                }
                MesShelfData mesShelfData = new MesShelfData();
                mesShelfData.setCell_num(shelfCode);//货架编码
                mesShelfData.setIndex(1);
                mesShelfData.setColor(color);//颜色
                mesShelfData.setBlink(0);
                List<MesShelfData> list = map.get(mesShelfIpConfig.getShelfHost());
                if (list == null) {
                    list = new ArrayList<>();
                    list.add(mesShelfData);
                    map.put(mesShelfIpConfig.getShelfHost(), list);
                } else {
                    map.get(mesShelfIpConfig.getShelfHost()).add(mesShelfData);
                }
            }
        } else {
            return Result.error("没有找到物料在货架上的对应位置！请检查！");
        }
        map.keySet().forEach(host -> {
            MesShelfUtil.litShelfLight(host, ShelfLight(map.get(host)));
        });
//		MesShelfLight mesShelfLight = ShelfLight(shelfDataList);//封装成一个list集合
//		String url = "http://192.168.10.13:9999/RecvInterface";//智能货架的URl
//		MesShelfUtil.litShelfLight(url, mesShelfLight);
        return Result.ok("货架灯启动完毕");
    }

    /**
     * app扫描入库
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app扫描入库-自动匹配")
    @ApiOperation(value = "仓库管理—批号交易-app扫描入库-自动匹配", notes = "仓库管理—批号交易-app扫描入库-自动匹配")
    @PostMapping(value = "/addScanStoreAll")
    public Result<?> addScanStoreAll(@RequestBody MesStorageWholesale mesStorageWholesale) {
        //System.err.println(mesStorageWholesale);
        //请求参数shelfCode：无货架入库  wareSite
        if (mesStorageWholesale==null||StringUtils.isEmpty(mesStorageWholesale.getId())){
            Result.error("网络异常，扫描入库失败！请重新扫描！");
        }
        MesChiefdataMateriel mater = systemClient.queryByMcode(mesStorageWholesale.getProductCode());
        if (mater != null) {
            mesStorageWholesale.setRowNum(mater.getMaterielType());
        }
        boolean mark = mesStorageWholesaleService.addScanStoreAll(mesStorageWholesale);

        if (mark) {
            return Result.ok("扫描入库成功");
        }
        return Result.error("未匹配到该物料，扫描入库失败！");
    }

    /**
     * app扫描入库
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app扫描入库")
    @ApiOperation(value = "仓库管理—批号交易-app扫描入库", notes = "仓库管理—批号交易-app扫描入库")
    @PostMapping(value = "/addScanStore")
    public Result<?> addScanStore(@RequestBody MesStorageWholesale mesStorageWholesale) {
        System.err.println(mesStorageWholesale);
        //请求参数shelfCode：无货架入库  wareSite
        MesChiefdataMateriel mater = systemClient.queryByMcode(mesStorageWholesale.getProductCode());
        if (mater != null) {
            mesStorageWholesale.setRowNum(mater.getMaterielType());
        }
        boolean mark = mesStorageWholesaleService.addScanStore(mesStorageWholesale);
        if (mark) {
            return Result.ok("扫描入库成功");
        }
        return Result.error("扫描入库失败");
    }

    /**
     * app扫描发料
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app扫描发料")
    @ApiOperation(value = "仓库管理—批号交易-app扫描发料", notes = "仓库管理—批号交易-app扫描发料")
    @PostMapping(value = "/scanSendMateriel")
    public Result<?> scanSendMateriel(@RequestBody MesStorageWholesale mesStorageWholesale) {
        Result<?> result = mesStorageWholesaleService.scanSendMateriel(mesStorageWholesale);
        if (result.isSuccess()) {
            if (StringUtils.isNotBlank(mesStorageWholesale.getQuery4())) {//如果制令单id不为空，获取制令单子表物料数据做判断
//			判断已发数量是否大于0，如果大于则修改生产订单状态为发料完成
                boolean flag = produceClient.checkProductStatusByCommandBillId(mesStorageWholesale.getQuery4());
                if (flag) {
                    System.out.println("发料完成，修改生产订单状态成功！");
                } else {
                    System.out.println("发料未完成，未修改生产订单状态！");
                }
            }
            //若扫描发料，发的是货架上的物料，则货架灯需要自动关闭
            if (StringUtils.isNotBlank(mesStorageWholesale.getShelfCode()) && StringUtils.isNotBlank(mesStorageWholesale.getShelfState())) {
                //修改货架状态为1：已扫描
                MesStorageWholesale wholesale = mesStorageWholesaleService.getById(mesStorageWholesale.getQuery5());
                wholesale.setShelfState("1");
                mesStorageWholesaleService.updateById(wholesale);
                //扫描发料结束后，将货架的灯关掉
                List<MesShelfData> shelfDataList = new ArrayList<>();
                String shelfCode = wholesale.getShelfCode();
                MesShelfData mesShelfData = new MesShelfData();
                mesShelfData.setCell_num(shelfCode);//货架编码
                mesShelfData.setIndex(1);
                mesShelfData.setColor("black");//black：关闭货架灯
                mesShelfData.setBlink(0);
                shelfDataList.add(mesShelfData);
                MesShelfLight mesShelfLight = ShelfLight(shelfDataList);
                //固定URL地址，第三个货架（目前只有第三个货架网络已经调好）
                MesShelfIpConfig mesShelfIpConfig = mesShelfIpConfigService.lambdaQuery()
                        .eq(MesShelfIpConfig::getShelfCodePre, shelfCode.split("-")[0]).one();
                if (mesShelfIpConfig == null) {
                    Result.error("货架没有配置Host");
                }
                String url = mesShelfIpConfig.getShelfHost();
                try {
                    MesShelfUtil.litShelfLight(url, mesShelfLight);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
            //判断物料发送完了没有，修改状态为已完成  //制令单id
            String message = produceClient.getCommandBomBycommandbillId(mesStorageWholesale.getQuery4(),mesStorageWholesale.getProductCode());
            System.out.println("是否发料完成:"+message);
            if ("发料已完成".equals(message)) {//做灭灯操作
                sendLitLight(mesStorageWholesale.getProductCode(), "black");
            }
        }
        return result;
    }

    /**
     * app制令单扫描入库
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app制令单扫描入库")
    @ApiOperation(value = "仓库管理—批号交易-app制令单扫描入库", notes = "仓库管理—批号交易-app制令单扫描入库")
    @PostMapping(value = "/instructionScanStore")
    public Result<?> instructionScanStore(@RequestBody MesStorageWholesale mesStorageWholesale) {
        System.err.println("app制令单扫描入库入参:" + mesStorageWholesale);
        log.info("入参instructionScanStore>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //根据basecode去查询制令单bom信息
		/*MesCommandbillInfo mesCommandbillInfo = produceClient.getById(mesStorageWholesale.getBaseCode());

		String commandbillCode = mesCommandbillInfo.getCommandbillCode();//制令单号

		String baseRowNum = mesStorageWholesale.getBaseRownum();
		MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);

		//获取线程扫描id
		List<MesCourseScan> mesCourseScans = produceClient.queryByCommandbillCode(commandbillCode);
		System.out.println("============mesCourseScans=="+mesCourseScans.size());
		for (MesCourseScan mesCourseScan:mesCourseScans) {
			if(mesCourseScan.getScanContent().equals(mesStorageWholesale.getQuery4())){
				System.out.println("========"+mesCourseScan.getScanContent()+"====mesCourseScans2=="+mesStorageWholesale.getQuery4());
				//查询制令单信息用于修改
				MesCommandbillInfo commandbillinfo= produceClient.getById(mesCommandbillInfo.getId());//制令单id
				BigDecimal uninputNum = new BigDecimal(commandbillinfo.getUninputNum());
				BigDecimal ONE=new BigDecimal("1");
				BigDecimal uninputNum2 =  uninputNum.subtract(ONE);
				System.out.println("uninputNum2:"+uninputNum2);
				if(uninputNum2.compareTo(BigDecimal.ZERO) == -1){
					return Result.error("入库已完成！请检查！");
				}else if(uninputNum2.compareTo(BigDecimal.ZERO) == 0){
					//为0的话就入库完成
					commandbillinfo.setInputState("入库完成");

				}
				commandbillinfo.setUninputNum(uninputNum2.toString());
				produceClient.editCommand(commandbillinfo);

				mesCourseScan.setQuery4("1");
				produceClient.editItem(mesCourseScan);

				mesStorageWholesale.setQuery4(mesStorageWholesale.getId());//重复扫描检查
				mesStorageWholesale.setId(null);
				mesStorageWholesale.setCreateBy(sysUser.getUsername());//创建人设置
				mesStorageWholesale.setCreateTime(DateUtils.getDate());//创建时间设置
				mesStorageWholesaleService.save(mesStorageWholesale);
				//return Result.ok("扫描入库成功");
			}

		}
		//return Result.error("找不到数据！请检查！");*/

        if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseDockettype())) {
            //基本行号：物料凭证项目id
            String pCode = mesStorageWholesale.getProductCode();
            System.err.println(pCode);
            String baseRowNum = mesStorageWholesale.getBaseRownum();
            MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
            log.info("instructionScanStore>getById>mesCertificateItem>" + JSON.toJSONString(mesCertificateItem));

            if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                MesCommandbillInfo commandbillInfo = produceClient.getById(mesStorageWholesale.getBaseCode());
                if (ObjectHelper.isNotEmpty(commandbillInfo)) {
                    BigDecimal originalNum = new BigDecimal(mesCertificateItem.getInputNum());//凭证上的入库数量
                    String mCode = mesCertificateItem.getMaterielCode();//物料料号
                    String docketType = mesStorageWholesale.getBaseDockettype();//单据类型
                    System.err.println(mCode);
                    if (!pCode.equals(mCode) && !pCode.equals(commandbillInfo.getMechanismCode())) {
                        return Result.error("扫描的物料不符！请检查！");
                    } else {
                        //扫描重复检查
                        if (StringUtils.isNotBlank(mesStorageWholesale.getQuery4())) {
                            String scanSendId = mesStorageWholesale.getQuery4();
                            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("product_code", pCode).eq("query4", scanSendId).eq("base_dockettype", docketType);
                            MesStorageWholesale storageWholesale = mesStorageWholesaleService.getOne(queryWrapper);
                            log.info("instructionScanStore>>storageWholesale>" + JSON.toJSONString(storageWholesale));
                            if (storageWholesale != null) {
                                return Result.error("请勿重复扫描！");
                            } else {
                                if (StringUtils.isNotBlank(mesStorageWholesale.getBaseCode())) {
                                    log.info("instructionScanStore>getById>commandbillInfo>" + JSON.toJSONString(commandbillInfo));
                                    System.err.println(commandbillInfo);
                                    BigDecimal uninputNum = new BigDecimal(commandbillInfo.getUninputNum());//未入库数量
                                    if (StringUtils.isNoneBlank(mesStorageWholesale.getInwareNum())) {
                                        if (ObjectHelper.isEmpty(commandbillInfo.getClientName())) {
                                            return Result.error("制令单中没有客户信息，请检查！");
                                        }
                                        MesWarehouseArea mesWarehouseArea = mesWarehouseAreaService.getMesWarehouseAreaByClientName(commandbillInfo.getClientName());
                                        if (ObjectHelper.isEmpty(mesWarehouseArea)) {
                                            return Result.error("制令单中的客户没有分配区位，请检查！");
                                        }
                                        BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//扫描入库数量
                                        BigDecimal remainNum = uninputNum.subtract(receiveNum);//剩余数量 = 未入库数量 - 扫描入库数量
                                        if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                            return Result.error("请检查标签上的数量是否正确！");
                                        } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                                            commandbillInfo.setUninputNum(remainNum.toString());
                                            commandbillInfo.setState("完成");
                                            commandbillInfo.setGlazeState("上料完成");
                                            commandbillInfo.setInputState("入库完成");
                                            produceClient.editCommand(commandbillInfo);
                                            log.info("instructionScanStore>editCommand>commandbillInfo>" + JSON.toJSONString(commandbillInfo));
                                            //物料凭证项目修改
                                            BigDecimal storageNum = originalNum.add(receiveNum);
                                            mesCertificateItem.setInputNum(storageNum.toString());
                                            mesCertificateItem.setIfInspect("否");
                                            mesCertificateItemService.updateById(mesCertificateItem);
                                            log.info("instructionScanStore>updateById>mesCertificateItem>" + JSON.toJSONString(mesCertificateItem));
                                            //物料凭证状态修改
                                            String perkId = mesCertificateItem.getPerkId();
                                            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(perkId);
                                            log.info("instructionScanStore>getById>mesCertificatePerk>" + JSON.toJSONString(mesCertificatePerk));
                                            if (mesCertificatePerk != null) {
                                                mesCertificatePerk.setIfFinish("未完成");
                                                mesCertificatePerkService.updateById(mesCertificatePerk);
                                                log.info("instructionScanStore>updateById>mesCertificatePerk>" + JSON.toJSONString(mesCertificatePerk));
                                            }
                                            //生产订单修改 注释说明：入库只修改指令单信息，生产订单入库数据在查询的时候带出指令单的入库信息即可
                                            /*MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillInfo.getProduceId());
                                            log.info("instructionScanStore>queryMesProduceById>produce>" + JSON.toJSONString(produce));
                                            if (produce != null) {
                                                BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());//生产订单总数量
                                                BigDecimal inNum = grossNum.subtract(remainNum);
                                                produce.setInputNum(inNum.toString());
                                                produce.setRemainNum(remainNum.toString());
                                                produce.setState("入库完成");
                                                transactionClient.editProduce(produce);
                                                log.info("instructionScanStore>editProduce>produce>" + JSON.toJSONString(produce));
                                            }*/
                                            //库存修改操作
                                            QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
                                            wrapper.eq("materiel_code", mCode);
                                            wrapper.eq("area_code", mesWarehouseArea.getAreaCode());
                                            wrapper.eq("location_code", mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                                            MesStockManage stockManage = mesStockManageService.getOne(wrapper);
                                            log.info("instructionScanStore>getOne>stockManage>" + JSON.toJSONString(stockManage));
                                            if (stockManage != null) {
                                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                                BigDecimal stocknewNum = stockNum.add(receiveNum);
                                                stockManage.setStockNum(stocknewNum.toString());
                                                mesStockManageService.updateById(stockManage);
                                                log.info("instructionScanStore>updateById>stockManage>" + JSON.toJSONString(stockManage));
                                            } else {
                                                MesStockManage mesStockManage = new MesStockManage();
                                                mesStockManage.setMaterielCode(mCode);
                                                mesStockManage.setMaterielName(mesStorageWholesale.getProductName());
                                                mesStockManage.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                                mesStockManage.setUnit(mesStorageWholesale.getUnit());
                                                mesStockManage.setStockNum(receiveNum.toString());
                                                mesStockManage.setMinimum("0");
                                                mesStockManage.setAreaCode(mesWarehouseArea.getAreaCode());
                                                mesStockManage.setLocationCode(mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                                                mesStockManageService.save(mesStockManage);
                                                log.info("没有找到库存数据，进行新增");
                                            }

                                        } else {
                                            commandbillInfo.setUninputNum(remainNum + "");
                                            produceClient.editCommand(commandbillInfo);
                                            log.info("instructionScanStore>editCommand1>commandbillInfo>" + JSON.toJSONString(commandbillInfo));
                                            //物料凭证项目修改
                                            BigDecimal storageNum = originalNum.add(receiveNum);
                                            mesCertificateItem.setInputNum(storageNum.toString());
                                            mesCertificateItem.setIfInspect("否");
                                            mesCertificateItemService.updateById(mesCertificateItem);
                                            log.info("instructionScanStore>updateById1>mesCertificateItem>" + JSON.toJSONString(mesCertificateItem));
                                            //物料凭证状态修改
                                            String perkId = mesCertificateItem.getPerkId();
                                            MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(perkId);
                                            log.info("instructionScanStore>getById1>mesCertificatePerk>" + JSON.toJSONString(mesCertificatePerk));
                                            if (mesCertificatePerk != null) {
                                                mesCertificatePerk.setIfFinish("未完成");
                                                mesCertificatePerkService.updateById(mesCertificatePerk);
                                                log.info("instructionScanStore>updateById1>mesCertificatePerk>" + JSON.toJSONString(mesCertificatePerk));
                                            }
                                            //生产订单修改 注释说明：入库只修改指令单信息，生产订单入库数据在查询的时候带出指令单的入库信息即可
                                            /*MesOrderProduce produce = transactionClient.queryMesProduceById(commandbillInfo.getProduceId());
                                            log.info("instructionScanStore>queryMesProduceById1>produce>" + JSON.toJSONString(produce));
                                            if (produce != null) {
                                                BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());//生产订单总数量
                                                BigDecimal inNum = grossNum.subtract(remainNum);
                                                produce.setInputNum(inNum.toString());
                                                produce.setRemainNum(remainNum.toString());
                                                transactionClient.editProduce(produce);
                                                log.info("instructionScanStore>editProduce1>produce>" + JSON.toJSONString(produce));
                                            }*/

                                            //库存修改操作
                                            QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
                                            wrapper.eq("materiel_code", mCode);
                                            wrapper.eq("area_code", mesWarehouseArea.getAreaCode());
                                            wrapper.eq("location_code", mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                                            MesStockManage stockManage = mesStockManageService.getOne(wrapper);
                                            log.info("instructionScanStore>getOne1>stockManage>" + JSON.toJSONString(stockManage));
                                            if (stockManage != null) {
                                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                                BigDecimal stocknewNum = stockNum.add(receiveNum);
                                                stockManage.setStockNum(stocknewNum.toString());
                                                mesStockManageService.updateById(stockManage);
                                                log.info("instructionScanStore>updateById1>stockManage>" + JSON.toJSONString(stockManage));
                                            } else {
                                                MesStockManage mesStockManage = new MesStockManage();
                                                mesStockManage.setMaterielCode(mCode);
                                                mesStockManage.setMaterielName(mesStorageWholesale.getProductName());
                                                mesStockManage.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                                mesStockManage.setUnit(mesStorageWholesale.getUnit());
                                                mesStockManage.setStockNum(receiveNum.toString());
                                                mesStockManage.setMinimum("0");
                                                mesStockManage.setQuery5("成品");
                                                mesStockManage.setAreaCode(mesWarehouseArea.getAreaCode());
                                                mesStockManage.setLocationCode(mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                                                mesStockManageService.save(mesStockManage);
                                                log.info("没有找到库存数据，进行新增");
                                            }
                                        }
                                    }
                                } else {
                                    return Result.error("app页面传输数据错误！");
                                }
                            }
                        } else {
                            return Result.error("app页面传输数据错误！");
                        }
                    }
                } else {
                    return Result.error("没有找到制令单数据！请检查！");
                }
            }
        } else {
            return Result.error("找不到数据！请检查！");
        }
        if (StringUtils.isNotBlank(mesStorageWholesale.getId())) {
            mesStorageWholesale.setQuery4(mesStorageWholesale.getId());//重复扫描检查
        }
        mesStorageWholesale.setId(null);
        mesStorageWholesale.setCreateBy(sysUser.getUsername());//创建人设置
        mesStorageWholesale.setCreateTime(DateUtils.getDate());//创建时间设置
        log.info("结束保存instructionScanStore>save>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        mesStorageWholesaleService.save(mesStorageWholesale);
        return Result.ok("扫描入库成功");
    }

    /**
     * 远程调用新增批号交易信息
     *
     * @param mesStorageWholesale
     * @return
     */
    @PostMapping(value = "/scanCourseadd")
    public boolean scanCourseadd(@RequestBody MesStorageWholesale mesStorageWholesale) {
        return mesStorageWholesaleService.save(mesStorageWholesale);
    }

    /**
     * 根据query4查询该制令单的上料记录 并根据原有上料记录去转产数量记录 远程调用
     *
     * @param query4   原制令单id
     * @param synum    已使用数量
     * @param mcode    物料料号
     * @param basecode 转产的制令单bom的id
     * @param newid    转产的制令单id
     * @return
     */
    @GetMapping("/updateCommandbill")
    public String updateCommandbill(@RequestParam(name = "query4", required = true) String query4,
                                    @RequestParam(name = "synum", required = true) String synum,
                                    @RequestParam(name = "mcode", required = true) String mcode,
                                    @RequestParam(name = "basecode", required = true) String basecode,
                                    @RequestParam(name = "newid", required = true) String newid) {
        return mesStorageWholesaleService.updateCommandbill(query4,synum,mcode,basecode,newid);
    }

    /**
     * app 扫描收货
     *
     * @param id         批号交易id,二维码id
     * @param baseCode   采购订单子表id
     * @param baseRownum 物料凭证项目id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app扫描收货")
    @ApiOperation(value = "仓库管理—批号交易-app扫描收货", notes = "仓库管理—批号交易-app扫描收货")
    @GetMapping(value = "/addTakeDelivery")
    public Result<?> addTakeDelivery(@RequestParam(name = "id", required = true) String id,
                                     @RequestParam(name = "baseCode", required = true) String baseCode,
                                     @RequestParam(name = "baseRownum", required = true) String baseRownum) {
        MesStorageWholesale mesStorageWholesale = mesStorageWholesaleService.addTakeDelivery(id, baseCode, baseRownum);
        return Result.OK(mesStorageWholesale);
    }
    /**
     * app 扫描收货
     *
     * @param baseCode   采购订单子表id
     * @param baseRownum 物料凭证项目id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app一键收货")
    @ApiOperation(value = "仓库管理—批号交易-app一键收货", notes = "仓库管理—批号交易-app一键收货")
    @GetMapping(value = "/oneTakeDelivery")
    public Result<?> oneTakeDelivery(@RequestParam(name = "baseCode", required = true) String baseCode,
                                     @RequestParam(name = "baseRownum", required = true) String baseRownum) {
        synchronized (this) {
            mesStorageWholesaleService.oneTakeDelivery(baseCode, baseRownum);
            transactionClient.uploadUnreceiveNum(baseCode);
        }
        return Result.ok("一键收货成功！");
    }

    /**
     * app 扫描上料
     *
     * @param id        批号交易id,二维码id
     * @param commandId 制令单id
     * @param prekId    物料凭证id
     * @param passage   通道
     * @param feeder    菲达
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app扫描上料")
    @ApiOperation(value = "仓库管理—批号交易-app扫描上料", notes = "仓库管理—批号交易-app扫描收货")
    @GetMapping(value = "/addUnglaze")
    public Result<?> addUnglaze(@RequestParam(name = "id", required = true) String id,
                                @RequestParam(name = "commandId", required = true) String commandId,
                                @RequestParam(name = "prekId", required = true) String prekId,
                                @RequestParam(name = "passage", required = true) String passage,
                                @RequestParam(name = "feeder", required = true) String feeder) {

        MesStorageWholesale mesStorageWholesale = mesStorageWholesaleService.addUnglaze(id, commandId, prekId, passage, feeder);
        return Result.OK(mesStorageWholesale);
    }


    /**
     * 添加
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-添加")
    @ApiOperation(value = "仓库管理—批号交易-添加", notes = "仓库管理—批号交易-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesStorageWholesale mesStorageWholesale) {
        System.err.println(mesStorageWholesale);
        if (mesStorageWholesale.getBaseDockettype().equals("辅料入库")) {
            systemClient.Ancillarytooladd(mesStorageWholesale.getProductCode());
        } else if (mesStorageWholesale.getBaseDockettype().equals("制具入库")) {
            systemClient.Maketooladd(mesStorageWholesale.getProductCode());
        } else if (mesStorageWholesale.getBaseDockettype().equals("扫描制令单上料")) {
            mesStorageWholesaleService.save(mesStorageWholesale);
            return Result.ok("添加成功！");
        }
        System.err.println(mesStorageWholesale.getBaseRownum());
        String tdlCode = "";
        if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum())) {
            //基本行号：物料凭证项目id
            String pCode = mesStorageWholesale.getProductCode();
            System.err.println(pCode);
            String baseRowNum = mesStorageWholesale.getBaseRownum();
            MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
            if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                String mCode = mesCertificateItem.getMaterielCode();//物料料号
                System.err.println(mCode);
                //替代料验证
                MesCommandbillInfo commandbillinfo = produceClient.queryCommandbillByItemId(mesStorageWholesale.getBaseCode());

                MesWarehouseArea mesWarehouseArea = iMesWarehouseAreaService.getMesWarehouseAreaByClientName(commandbillinfo.getClientName());
                if (com.epms.util.ObjectHelper.isEmpty(mesWarehouseArea)) {
                    return Result.error("该制令单的客户名称未找到对应的库区库位，请检查！");
                }else{
                    mesStorageWholesale.setLocationCode(mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                    mesStorageWholesale.setAreaCode(mesWarehouseArea.getAreaCode());
                }

                List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillinfo.getMechanismCode(), mCode, pCode);
                if (replacematerials.size() > 0) {
                    mesStorageWholesale.setProductCode(mCode);
                    tdlCode = "替代料:" + pCode;
                }
                if (!pCode.equals(mCode) && replacematerials.size() == 0) {
                    this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "扫描的物料不符！请检查！", mesStorageWholesale.getQuery4());
                    return Result.error("扫描的物料不符！请检查！");
                }
            }
        } else {
            return Result.error("找不到数据！请检查！");
        }
        System.err.println("mesStorageWholesale============" + mesStorageWholesale);
        //扫描重复检查
        if (StringUtils.isNotBlank(mesStorageWholesale.getQuery4())) {
            String swId = mesStorageWholesale.getQuery4();
            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("query4", swId);
            MesStorageWholesale storageWholesale = mesStorageWholesaleService.getOne(queryWrapper);
            if (storageWholesale != null) {
                return Result.error("请勿重复扫描！");
            }
        } else if (StringUtils.isNotBlank(mesStorageWholesale.getQuery5())) {
            String swId = mesStorageWholesale.getQuery5();
            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("query5", swId);
            MesStorageWholesale storageWholesale = mesStorageWholesaleService.getOne(queryWrapper);
            if (storageWholesale != null) {
                return Result.error("请勿重复扫描！");
            }
        } else if (StringUtils.isNotBlank(mesStorageWholesale.getGlazeId())) {
            String glazeId = mesStorageWholesale.getGlazeId();
            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("glaze_id", glazeId);
            List<MesStorageWholesale> list = mesStorageWholesaleService.list(queryWrapper);
            if (list.size() > 0) {
                this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "请勿重复扫描！", mesStorageWholesale.getQuery4());
                return Result.error("请勿重复扫描！");
            }
        }
        MesPurchaseItem purchaseItem = null;
        MesCommandbillInfo commandbillInfo = null;
        MesCommandbillPitem commandbillPitem = null;
        MesProduceItem produceItem = null;
        MesSaleItem saleItem = null;
        commandbillPitem = produceClient.queryPitemById(mesStorageWholesale.getBaseCode());
        if (commandbillPitem == null) {
            commandbillInfo = produceClient.getById(mesStorageWholesale.getBaseCode());
            if (commandbillInfo == null) {
                produceItem = transactionClient.queryMesProduceItemById(mesStorageWholesale.getBaseCode());
                if (produceItem == null) {
                    saleItem = transactionClient.queryMesSaleItemById(mesStorageWholesale.getBaseCode());
                    if (saleItem == null) {
                        purchaseItem = transactionClient.queryMesPurchaseItemById(mesStorageWholesale.getBaseCode());
                    }
                }
            }
        }

        //通过基本行号，找到相应的数据
        System.err.println("baseCode=================" + mesStorageWholesale.getBaseCode());
//		//采购订单
//		MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(mesStorageWholesale.getBaseCode());
//		//制令单信息
//		MesCommandbillInfo commandbillInfo = produceClient.getById(mesStorageWholesale.getBaseCode());
//		//制令单BOM项目
//		MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesStorageWholesale.getBaseCode());
//		//生产订单
//		MesProduceItem produceItem = transactionClient.queryMesProduceItemById(mesStorageWholesale.getBaseCode());
//		//销售订单
//		MesSaleItem saleItem = transactionClient.queryMesSaleItemById(mesStorageWholesale.getBaseCode());

        if (purchaseItem != null) {//采购订单
            String baseRowNum = mesStorageWholesale.getBaseRownum();//物料凭证项目
            BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
            if (StringUtils.isNoneBlank(mesStorageWholesale.getInwareNum())) {
                BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//入库数量
                BigDecimal remainNum = unreceiveNum.subtract(receiveNum);//可收货数量=未收货数量-入库数量
                if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                    //this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "请检查收货数量是否正确！", mesStorageWholesale.getQuery4());
                    return Result.error("请检查收货数量是否正确！");
                } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                    purchaseItem.setUnreceiveNum(remainNum.toString());
                    purchaseItem.setIfFinish("收货完成");
                    transactionClient.editPurchaseItem(purchaseItem);
                    //收货完成，向工作人员发送质检提醒；目前测试环境，向当前登录用户发送消息提醒，上线后修改
//					LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//					systemClient.sendCheckMessage(sysUser.getUsername(),purchaseItem.getMaterielName(),purchaseItem.getPurchaseNum(),purchaseItem.getOrderUnit());
                    asyncUtils.asyncSend(purchaseItem);

                    MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
                    String perkId = mesCertificateItem.getPerkId();
                    MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                    if (certificatePerk != null) {
                        certificatePerk.setIfFinish("未完成");
                        mesCertificatePerkService.updateById(certificatePerk);
                    }
                } else {
                    purchaseItem.setUnreceiveNum(remainNum.toString());
                    transactionClient.editPurchaseItem(purchaseItem);
                }
            }
            mesStorageWholesale.setWareCode(purchaseItem.getFactoryCode());//工厂编号
            mesStorageWholesale.setQuery2(purchaseItem.getFactoryName());//工厂名称
            mesStorageWholesale.setWareSite(purchaseItem.getStorageSite());//存储位置
        } else if (commandbillInfo != null) {//制令单信息
            System.err.println(commandbillInfo);

//			BigDecimal planNum = new BigDecimal(commandbillInfo.getPlantNum());//计划数量

            BigDecimal uninputNum = new BigDecimal(commandbillInfo.getUninputNum());//未入库数量
            BigDecimal totle = new BigDecimal(commandbillInfo.getPlantNum());//计划数量
            if (StringUtils.isNoneBlank(mesStorageWholesale.getInwareNum())) {
                BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//扫描入库数量
                BigDecimal remainNum = uninputNum.add(receiveNum);//已上料数量 = 未入库数量 + 扫描入库数量
                System.out.println(uninputNum + "======111====" + receiveNum + "======2222====" + remainNum);
                if (totle.compareTo(remainNum) == -1) {
                    //this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "请检查标签上的数量是否正确！", mesStorageWholesale.getQuery4());
                    return Result.error("请检查标签上的数量是否正确！");
                } else if (remainNum.compareTo(totle) == 0) {
                    commandbillInfo.setUninputNum(remainNum.toString());
                    commandbillInfo.setInputState("入库完成");
                    produceClient.editCommand(commandbillInfo);
                } else {
                    commandbillInfo.setUninputNum(remainNum + "");
                    produceClient.editCommand(commandbillInfo);
                }
            }
        } else if (produceItem != null) {//生产订单
            System.err.println("你的思路是对的！");
            BigDecimal deliveryNum = new BigDecimal(produceItem.getDeliveryNum());//已发料数量
            if (StringUtils.isNoneBlank(mesStorageWholesale.getInwareNum())) {
                BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//扫描发料数量
                BigDecimal remainNum = deliveryNum.add(receiveNum);//剩余数量
                produceItem.setDeliveryNum(remainNum.toString());
                transactionClient.editProduceItem(produceItem);
            }
        } else if (saleItem != null) {//销售订单
            String mCode = saleItem.getMaterielCode();//物料料号
            //通过料号查询库存数据
            QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("materiel_code", mCode);
            MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
            if (stockManage != null) {
                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//扫描发料数量
                BigDecimal stockNewNum = stockNum.subtract(receiveNum);//新库存数量 = 库存数量 - 扫描发料数量
                if (stockNewNum.compareTo(BigDecimal.ZERO) == -1) {
                    //this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "库存数量不足！请检查！", mesStorageWholesale.getQuery4());
                    return Result.error("库存数量不足！请检查！");
                } else {
                    BigDecimal undeliveryNum = new BigDecimal(saleItem.getUndeliveryNum());//未发货数量
                    BigDecimal remainNum = undeliveryNum.subtract(receiveNum);//剩余数量 = 未发货数量 - 扫描发料数量
                    if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                        //this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "数量不符！请检查！", mesStorageWholesale.getQuery4());
                        return Result.error("数量不符！请检查！");
                    } else if (remainNum.compareTo(BigDecimal.ZERO) == 0) {
                        saleItem.setUndeliveryNum(remainNum + "");
                        saleItem.setState("完成");//全部发货完成，改变销售订单状态为完成
                        String saleId = saleItem.getSaleorderId();
                        MesOrderSale mesOrderSale = transactionClient.queryMesSaleOrderById(saleId);
                        if (mesOrderSale != null) {
                            mesOrderSale.setState("完成");
                            transactionClient.editSaleOrder(mesOrderSale);
                        }
                        transactionClient.editSaleItem(saleItem);
                    } else {
                        saleItem.setUndeliveryNum(remainNum + "");
                        transactionClient.editSaleItem(saleItem);
                    }
                    stockManage.setStockNum(stockNewNum.toString());
                    mesStockManageService.updateById(stockManage);
                }
            } else {
                this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "没有找到库存数据！请检查！", mesStorageWholesale.getQuery4());
                return Result.error("没有找到库存数据！请检查！");
            }
        } else if (commandbillPitem != null) {//制令单BOM项目
            System.err.println("批号交易=================" + mesStorageWholesale);
            System.err.println("制令单BOM=================" + commandbillPitem);
            String orderId = commandbillPitem.getProorderId();//生产订单id
            String mCode = commandbillPitem.getMaterielCode();//物料料号
            String commandbillId = commandbillPitem.getCommandbillId();//制令单id
            BigDecimal printNum = new BigDecimal(mesStorageWholesale.getInwareNum());//打印标签上的数量
            //制令单扫描上料
            if (mesStorageWholesale.getBaseDockettype().equals("扫描上料")) {
                MesStorageWholesale storageWholesale = mesStorageWholesaleService.getById(mesStorageWholesale.getGlazeId());
                mesStorageWholesale.setInwareNum(storageWholesale.getInwareNum());
                BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                BigDecimal glazeNum = new BigDecimal(commandbillPitem.getUnglazeNum());//已上料数量
                BigDecimal inputNum = new BigDecimal(storageWholesale.getInwareNum());//扫描上料数量
                BigDecimal glaeNewNum = glazeNum.add(inputNum);//新上料数量 = 已上料数量 + 扫描上料数量
                if (glaeNewNum.compareTo(deliveryNum) == 1) {
                    this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "发料数量不足！请先发料！", mesStorageWholesale.getQuery4());
                    return Result.error("发料数量不足！请先发料！");
                } else {
                    MesCommandbillInfo mesCommandbillInfo = produceClient.getById(commandbillId);

                    //feeder编号
                    String feeder = mesStorageWholesale.getQuery2().trim();
                    //判断类型为SMT的才验证feeder
                    String produceGrade = mesCommandbillInfo.getProduceGrade();//线别
                    if (!"SMT".equals(produceGrade)) {
                        feeder = "无feeder";
                    }

                    if (!"无feeder".equals(feeder)) {
                        if (StringUtils.isBlank(feeder)) {
                            this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "feeder为空！请检查！", mesStorageWholesale.getQuery4());
                            return Result.error("feeder为空！请检查！");
                        }
                        //添加feeder使用点数的信息，便于后期维护
						/*MesChiefdataFeeder mesChiefdataFeeder = systemClient.getfeederComitem(feeder);//根据sn获取feeder信息
						if (mesChiefdataFeeder == null) {
							return Result.error("没有找到该feeder信息！请检查！");
						}*/

                        //判断上料是否达到预警值，达到了就发送停机
						/*BigDecimal requireNum = new BigDecimal(mesCommandbillInfo.getPlantNum());//计划数量

						String remindRate = mesCommandbillInfo.getGlazeRemind();//上料提醒比例
						remindRate = remindRate.substring(0, remindRate.length() - 1);  //去掉“%”
						BigDecimal rate = new BigDecimal(remindRate);
						BigDecimal remind = rate.divide(new BigDecimal(100), 3, RoundingMode.HALF_UP);//除以100，获取小数值
						BigDecimal remindNum = requireNum.multiply(remind);//剩余数量 = 计划数量 * 上料提醒比例
						BigDecimal reachNum = requireNum.subtract(remindNum);//到达提醒的数量 = 计划数量 - 剩余数量
						System.err.println(reachNum);
						if (reachNum.compareTo(glaeNewNum) == 0) {
							//根据制令单bom的产线编号去查询该产线的产线id
							String lineType = mesCommandbillInfo.getLineType();//产线编号
							MesChiefdataProductline mesChiefdataProductline = systemClient.queryByLineCode(lineType);
							if (mesChiefdataProductline != null) {
								//停机
								systemClient.stopById(mesChiefdataProductline.getId(), "30");
							} else {
								return Result.error("产线数据有误，无法停机！请检查！");
							}
						}*/
                    }
                    //上料上错了通道 停机
                    String passage = mesStorageWholesale.getWareSite();//通道
                    if (!"无通道".equals(passage)) {
                        //MesCommandbillPitem commandbillPitem1 = produceClient.queryPitemById(mesStorageWholesale.getGlazeId());

                        MesOnlineMaterieltable mesOnlineMaterieltable = produceClient.queryBylineType(mesCommandbillInfo.getMechanismCode(), commandbillPitem.getMaterielCode(), mesCommandbillInfo.getLineType(), passage);
                        if (mesOnlineMaterieltable != null&&mesOnlineMaterieltable.getPassage()!=null) {
                            //通道不对应停机
                            if (!mesOnlineMaterieltable.getPassage().equals(passage)) {
                                //根据制令单bom的产线编号去查询该产线的产线id
                                String lineType = mesCommandbillInfo.getLineType();//产线编号
                                MesChiefdataProductline mesChiefdataProductline = systemClient.queryByLineCode(lineType);
                                if (mesChiefdataProductline != null) {
                                    //停机
                                    systemClient.stopById(mesChiefdataProductline.getId(), "30");
                                    this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "物料通道有误！请检查！", mesStorageWholesale.getQuery4());
                                    return Result.error("物料通道有误！请检查！");
                                } else {
                                    this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "产线数据有误，无法停机！请检查！", mesStorageWholesale.getQuery4());
                                    return Result.error("产线数据有误，无法停机！请检查！");
                                }
                            }
                        } else {
                            this.recordErrorOperation("/storage/mesStorageWholesale/add", "制令单上料", "仓库管理—批号交易-添加", "物料通道配置有误！请检查！", mesStorageWholesale.getQuery4());
                            return Result.error("物料通道配置有误！请检查！");
                        }
                    }
                    commandbillPitem.setUnglazeNum(glaeNewNum.toString());
                    produceClient.editComitem(commandbillPitem);

                    mesStorageWholesale.setProductName(storageWholesale.getProductName());
                    mesStorageWholesale.setQuery2("feeder: " + feeder);
                    mesStorageWholesale.setQuery4(commandbillPitem.getCommandbillId());
                    mesStorageWholesale.setWareSite("通道: " + passage);
                    mesStorageWholesale.setInwareNum(storageWholesale.getInwareNum());
                    mesStorageWholesale.setUnit(storageWholesale.getUnit());

                    String baseRowNum = mesStorageWholesale.getBaseRownum();
                    MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
                    mesCertificateItem.setFactoryCode(mesStorageWholesale.getWareCode());
                    mesCertificateItem.setFactoryName(mesStorageWholesale.getQuery2());
                    mesCertificateItem.setStorageSite(mesStorageWholesale.getWareSite());
                    mesCertificateItemService.updateById(mesCertificateItem);

                }
            }
            //制令单扫描退料
            if (mesStorageWholesale.getBaseDockettype().equals("扫描退料")) {
                System.err.println("你找到了扫描退料模块！");
                BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
                BigDecimal originalNum = new BigDecimal(commandbillPitem.getWithdrawNum());//原有数量
                BigDecimal withdrawNum = originalNum.add(printNum);//新的退料数量=原有数量 + 退料数量（打印标签上的数量）
                BigDecimal remainNum = deliveryNum.subtract(withdrawNum);
                if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                    return Result.error("数量不符！请检查！");
                } else {
                    //通过订单id和物料料号，获取物料领用数据
                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                    if (mesMaterielOccupy != null) {
//						BigDecimal originalNum = new BigDecimal(mesMaterielOccupy.getWithdrawNum());//原有的数量
//						BigDecimal withdrawNum = originalNum.add(inputNum);//新的退料数量 = 原有数量 + 退料数量
                        //退料更新库存操作
                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("materiel_code", mCode);
                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                        if (stockManage != null) {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                            BigDecimal stockNewNum = stockNum.add(printNum);//新库存数量 = 库存数量 + 退料数量
                            stockManage.setStockNum(stockNewNum.toString());
                            mesStockManageService.updateById(stockManage);
                            //更新领料表的退料数量
                            mesMaterielOccupy.setWithdrawNum(withdrawNum.toString());
                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                            //更新制令单Bom表的退料数量
                            commandbillPitem.setWithdrawNum(withdrawNum.toString());
                            produceClient.editComitem(commandbillPitem);
                        } else {
                            return Result.error("没有找到库存数据！请检查！");
                        }

                    } else {
                        return Result.error("没有找到物料领用信息！请检查！");
                    }
                }
            } else if (mesStorageWholesale.getBaseDockettype().equals("扫描发料")) {
                //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", mCode);
                MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                if (mesMaterielOccupy != null) {
                    BigDecimal unUsedNum = new BigDecimal(mesMaterielOccupy.getUnusedNum());//未使用数量
                    BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                    if (unUsedNum.compareTo(printNum) == -1) {//物料超发
                        System.err.println("你的思路是对的！");
                        BigDecimal usedStockNum = printNum.subtract(unUsedNum);//超发的数量
                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("materiel_code", mCode);
                        MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                        if (stockManage == null) {
                            return Result.error("查不到库存数据！请检查！");
                        } else {
                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                            BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                            BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                            //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                            if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                return Result.error("库存数量不足！请检查！");
                            } else {
                                stockManage.setStockNum(remainNum.toString());//新的库存数量 = 剩余数量
                                mesStockManageService.updateById(stockManage);
                                //如果库存数量小于库存临界点，则给用户发送消息提醒
                                if (remainNum.compareTo(minimum) < 1) {
                                    // 获取登录用户信息
                                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                    System.err.println(sysUser);
                                    //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                    systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                }
                                BigDecimal num = deliveryNum.add(printNum);//新的发料数量 = 原有数量+ 打印标签上的数量（发料数量）
                                commandbillPitem.setDeliveryNum(num.toString());
                                produceClient.editComitem(commandbillPitem);
                                //更新领料表数据
                                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                                mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                mesMaterielOccupy.setUnusedNum("0");
                                mesMaterielOccupyService.updateById(mesMaterielOccupy);
                            }
                        }
                    } else {//未超发
                        BigDecimal remainNum = unUsedNum.subtract(printNum);//剩余数量 = 未领用数量- 打印标签上的数量（发料数量）
                        BigDecimal num = deliveryNum.add(printNum);//新的已发料数量 = 原有数量+ 打印标签上的数量（发料数量）
                        commandbillPitem.setDeliveryNum(num.toString());
                        produceClient.editComitem(commandbillPitem);
                        //更新领料表数据
                        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                        mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                        mesMaterielOccupy.setSendNum(num.toString());//发料数量
                        mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                        mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                        mesMaterielOccupyService.updateById(mesMaterielOccupy);
                    }
                } else {
                    return Result.error("找不到物料领用数据！请检查！");
                }
            }
        } else {
            return Result.error("请检查打印的标签是否正确！");
        }
        if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum())) {
            //基本行号：物料凭证项目id
            String pCode = mesStorageWholesale.getProductCode();
            String baseRowNum = mesStorageWholesale.getBaseRownum();
            MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
            System.err.println("mesCertificateItem===============" + mesCertificateItem);
            if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                String mCode = mesCertificateItem.getMaterielCode();//物料料号
                if (pCode.equals(mCode)) {
                    if (StringUtils.isNotBlank(mesStorageWholesale.getInwareNum())) {
                        BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());
                        BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());
                        BigDecimal newInputNum = inputNum.add(inwareNum);
                        mesCertificateItem.setInputNum(newInputNum.toString());
                        mesCertificateItem.setUnstorageNum(newInputNum.toString());
                        //201 制令单扫描入库
                        if (mesCertificateItem.getMobileCode().equals("201")) {
//							mesCertificateItem.setIfInspect("否");//制令单入库时，设为未质检
                            QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("materiel_code", mCode);
                            MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
                            if (stockManage != null) {
                                if (StringUtils.isNotBlank(stockManage.getStockNum())) {
                                    BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                    BigDecimal totalNum = stockNum.add(inwareNum);
                                    stockManage.setStockNum(totalNum.toString());
                                    mesStockManageService.updateById(stockManage);
                                } else {
                                    return Result.error("料号为 " + mesCertificateItem.getMaterielCode() + "的" + mesCertificateItem.getMaterielName() + "库存数量不能为空！");
                                }
                            } else {
                                MesStockManage mesStockManage = new MesStockManage();
                                BeanUtils.copyProperties(mesCertificateItem, mesStockManage);
                                mesStockManage.setId(null);//主键设置为null
//								mesStockManage.setCreateBy(null);//创建人设置为null
//								mesStockManage.setCreateTime(null);//创建时间设置为null
                                mesStockManage.setStoreName(mesCertificateItem.getStorageSite());
                                mesStockManage.setUnit(mesCertificateItem.getInputUnit());
                                mesStockManage.setStockNum(inwareNum.toString());
                                MesChiefdataMateriel mater = systemClient.queryByMcode(mesStockManage.getMaterielCode());
                                if (mater != null) {
                                    mesStockManage.setQuery5(mater.getMaterielType());
                                }
                                mesStockManageService.save(mesStockManage);
                            }
                        }
                    }
                    mesStorageWholesale.setQuery3(mesCertificateItem.getPerkId());//物料凭证项目id
                    mesCertificateItemService.updateById(mesCertificateItem);
                } else {
                    return Result.error("扫描的物料不符！请检查！");
                }
            }
        } else {
            return Result.error("找不到数据！请检查！");
        }
        //替代料记录
        if (StringUtils.isNotBlank(tdlCode)) {
            mesStorageWholesale.setQuery5(tdlCode);
        }
        if (commandbillPitem != null) {//制令单BOM项目
            //判断是否上料完成
            String message=produceClient.getCommandBomBycommandbillId(commandbillPitem.getCommandbillId(),commandbillPitem.getMaterielCode());
            System.out.println("是否上料完成:"+message);
            mesStorageWholesaleService.addUnglaze(mesStorageWholesale);
        }else{
            mesStorageWholesaleService.save(mesStorageWholesale);
        }
        return Result.ok("扫描成功！");

    }

    /**
     * app打印添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-app打印添加")
    @ApiOperation(value = "仓库管理—批号交易-app打印添加", notes = "仓库管理—批号交易-app打印添加")
    @GetMapping(value = "/printAdd")
    public Result<?> printAdd(@RequestParam(name = "id", required = false) String id,
                              @RequestParam(name = "commandId", required = false) String commandId,
                              @RequestParam(name = "cPid", required = false) String cPid,
                              @RequestParam(name = "batch", required = true) String batch,
                              @RequestParam(name = "printNum", required = true) int printNum,
                              @RequestParam(name = "mobileType", required = false) String mobileType,
                              @RequestParam(name = "clientCode", required = false) String clientCode,
                              @RequestParam(name = "batchNum", required = false) String batchNum,
                              @RequestParam(name = "remark", required = false) String remark) {
        if (printNum > 10) {
            return Result.error("一次打印张数，最多可打印10张！");
        }
        if (StringUtils.isNotBlank(commandId)) {
            //通过制令单id，调用生产模块。获取制令单信息
            MesCommandbillInfo commandbillInfo = produceClient.getById(commandId);
            BigDecimal planNum = new BigDecimal(commandbillInfo.getPlantNum());//计划数量
            BigDecimal batchnum = new BigDecimal(batch);//批次数量
            BigDecimal printPaper = new BigDecimal(printNum);//打印张数
            BigDecimal totalNum = batchnum.multiply(printPaper);//打印总数：打印张次*数量
            //打印的总数量不能大于未收货数量
            if (totalNum.compareTo(planNum) == 1) {
                return Result.error("打印总数超过计划数量！请您再次确认！");
            }
            String pid = commandbillInfo.getId(); //制令单id
            String mcode = commandbillInfo.getMechanismCode(); //物料编号
            String mname = commandbillInfo.getMechanismName(); //物料名称
            String orderId = commandbillInfo.getProduceId();
            List<MesStorageWholesale> list = new ArrayList<>();
            //根据printNum打印次数，进行循环
            for (int i = 0; i < printNum; i++) {
                synchronized (this) {
                    //批号交易类
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    String dateString = formatter.format(DateUtils.getDate());
                    MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();
                    mesStorageWholesale.setQuery1(dateString);//当前时间
                    if (StringUtils.isNotBlank(batchNum)) {
                        mesStorageWholesale.setBatchNum(batchNum);//批次号
                    } else {
                        //为空，默认为当天时间
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        mesStorageWholesale.setBatchNum(sdf.format(DateUtils.getDate()));//批次号
                    }
                    if (StringUtils.isNotBlank(clientCode)) {
                        mesStorageWholesale.setClientCode(clientCode);//客户料号
                    } else {
                        //获取客户料号
                        MesChiefdataMateriel mesChiefdataMateriel = systemClient.queryByMcode(mcode);
                        mesStorageWholesale.setClientCode(mesChiefdataMateriel.getQuery2());//客户料号
                    }
                    if (StringUtils.isBlank(mesStorageWholesale.getClientCode())) {
                        mesStorageWholesale.setClientCode("未录入");
                    }
                    mesStorageWholesale.setBaseCode(pid);//采购订单子表id
                    mesStorageWholesale.setBaseDockettype(mobileType);//打印类型
                    mesStorageWholesale.setProductCode(mcode);//料号
                    mesStorageWholesale.setProductName(mname);//品名
                    MesOrderProduce produce = transactionClient.queryMesProduceById(orderId);
                    if (produce != null) {
                        mesStorageWholesale.setUnit(produce.getUnit());//单位
                        mesStorageWholesale.setWareCode(produce.getFactoryCode());//工厂编号
                        mesStorageWholesale.setQuery2(produce.getFactoryName());//工厂名称
                        mesStorageWholesale.setWareSite(produce.getStorageSite());//存储位置
                    }
                    mesStorageWholesale.setInwareNum(batch); //每批的数量
                    //每打印一张，就往批号交易表里新增一条数据
                    mesStorageWholesaleService.save(mesStorageWholesale);
                    list.add(mesStorageWholesale);

                    // 获取随机字符串
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    int random = RandomUtils.nextInt(90) + 10;
                    String randomNo = format.format(new Date()) + random;

                    //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
                    MesPrintModel printModel = systemClient.queryByPrintType(mobileType);
                    if (printModel != null) {
                        try {
                            executor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    //coHead打印的实体类
                                    conHead conHead = new conHead();
                                    //二维码字段，存放批号交易id
                                    conHead.setConBy1(mesStorageWholesale.getId());
                                    //随机字符串，用于文件的命名
                                    conHead.setOrderNo(randomNo);
                                    conHead.setConNo(randomNo);
                                    // contempPath：打印模版的url路径，一般是word文档，存在minio里
                                    conHead.setContempPath(printModel.getPrintModel());
                                    List<conmap> conmapList = new ArrayList<>();//打印字段
                                    //将批号交易类实体转成map,以K,V形式存取
                                    Map map = JSON.parseObject(JSON.toJSONString(mesStorageWholesale), Map.class);
                                    System.err.println(map);
                                    //遍历Map，取到Key和Value
                                    map.forEach((key, value) -> {
                                        System.err.println("1key=" + key + ",value=" + value);
                                        //conmap 打印字段实体类
                                        conmap conmap = new conmap();
                                        //根据key,将打印模版的{key}转换成value
                                        conmap.setConKey(key.toString());
                                        conmap.setConValue(value.toString());
                                        conmapList.add(conmap);
                                    });
                                    //将采购订单子表实体转成map，以K,V形式存取，做上面一样的操作
                                    Map purchaseMap = JSON.parseObject(JSON.toJSONString(commandbillInfo), Map.class);
                                    System.err.println(purchaseMap);
                                    purchaseMap.forEach((key, value) -> {
                                        System.err.println("2key=" + key + ",value=" + value);
                                        conmap conmap = new conmap();
                                        conmap.setConKey(key.toString());
                                        conmap.setConValue(value.toString());
                                        conmapList.add(conmap);
                                    });
                                    conHead.setConmapList(conmapList);
                                    try {
                                        //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                                        mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);

                                    } catch (Exception e) {

                                    }
                                }
                            });
                        } catch (Exception e) {

                        }

                    } else {
                        return Result.error("没有找到打印模版的数据！请检查！");
                    }
                }
            }
        } else if (StringUtils.isNotBlank(id)) {
            // 通过id,远程调用业务模块，将采购订单子表数据传过来
            MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(id);
            MesChiefdataMateriel material = systemClient.queryByMcode(purchaseItem.getMaterielCode());
            if (material != null) {
                purchaseItem.setQuery6(StringUtils.isEmpty(material.getSupplier()) ? "无" : material.getSupplier());
            }
            if (StringUtils.isNotEmpty(purchaseItem.getMaterielGauge()) && purchaseItem.getMaterielGauge().length() > 50) {
                purchaseItem.setMaterielGauge(purchaseItem.getMaterielGauge().substring(0, 50));
            }
            purchaseItem.setQuery4(StringUtils.isEmpty(remark) ? "无" : remark);
            BigDecimal purchaseNum = new BigDecimal(purchaseItem.getPurchaseNum()); //采购数量
            BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
            BigDecimal batchnum = new BigDecimal(batch);//批次数量
            BigDecimal printPaper = new BigDecimal(printNum);//打印张数
            BigDecimal totalNum = batchnum.multiply(printPaper);//打印总数：打印张次*数量
            //打印的总数量不能大于未收货数量
            if (totalNum.compareTo(unreceiveNum) == 1) {
                return Result.error("打印总数超过未收货数量，请您再次确认！");
            }
            String pid = purchaseItem.getId(); //采购订单子表id
//            String rowNum = purchaseItem.getRowNum(); //误差
            String mcode = purchaseItem.getMaterielCode(); //物料编号
            String mname = purchaseItem.getMaterielName(); //物料名称
            String factoryCode = purchaseItem.getFactoryCode();//工厂编号
            String factoryName = purchaseItem.getFactoryName();//工厂名称
            String storageSite = purchaseItem.getStorageSite();//物料名称
            String unit = purchaseItem.getOrderUnit(); //单位
//		 String type ="入库打印";
            List<MesStorageWholesale> list = new ArrayList<>();
            //根据printNum打印次数，进行循环
            for (int i = 0; i < printNum; i++) {
                synchronized (this) {
                    //批号交易类
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    String dateString = formatter.format(new Date());
                    MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();
//                    mesStorageWholesale.setBaseRownum(rowNum);//误差
                    mesStorageWholesale.setBaseCode(pid);//采购订单子表id
                    mesStorageWholesale.setBaseDockettype(mobileType);//打印类型
                    mesStorageWholesale.setProductCode(mcode);//料号
                    mesStorageWholesale.setProductName(mname);//品名
                    mesStorageWholesale.setUnit(unit);//单位
                    mesStorageWholesale.setQuery1(dateString);//当前时间
                    mesStorageWholesale.setWareCode(factoryCode);//工厂编号
                    mesStorageWholesale.setQuery2(factoryName);//工厂名称
                    if (StringUtils.isNotBlank(batchNum)) {
                        mesStorageWholesale.setBatchNum(batchNum);//批次号
                    } else {
                        mesStorageWholesale.setBatchNum("  ");//批次号
                    }
                    if (StringUtils.isNotBlank(clientCode)) {
                        mesStorageWholesale.setClientCode(clientCode);//客户料号
                    } else {
                        MesChiefdataMateriel materiel = systemClient.queryByMcode(mcode);
                        if (materiel != null) {
                            mesStorageWholesale.setClientCode(materiel.getQuery2());//客户料号
                        }
                    }
                    mesStorageWholesale.setWareSite(storageSite);//存储位置
                    mesStorageWholesale.setInwareNum(batch); //每批的数量
                    //每打印一张，就往批号交易表里新增一条数据
                    mesStorageWholesaleService.save(mesStorageWholesale);
                    list.add(mesStorageWholesale);

                    // 获取随机字符串
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    int random = RandomUtils.nextInt(90) + 10;
                    String randomNo = format.format(new Date()) + random;

                    //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
                    MesPrintModel printModel = systemClient.queryByPrintType(mobileType);
                    if (printModel != null) {
                        try {
                            executor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    //coHead打印的实体类
                                    conHead conHead = new conHead();
                                    //二维码字段，存放批号交易id
                                    conHead.setConBy1(mesStorageWholesale.getId());
                                    //随机字符串，用于文件的命名
                                    conHead.setOrderNo(randomNo);
                                    conHead.setConNo(randomNo);
                                    // contempPath：打印模版的url路径，一般是word文档，存在minio里
                                    conHead.setContempPath(printModel.getPrintModel());
                                    List<conmap> conmapList = new ArrayList<>();//打印字段
                                    //将批号交易类实体转成map,以K,V形式存取
                                    Map map = JSON.parseObject(JSON.toJSONString(mesStorageWholesale), Map.class);
                                    System.err.println(map);
                                    //遍历Map，取到Key和Value
                                    map.forEach((key, value) -> {
                                        System.err.println("3key=" + key + ",value=" + value);
                                        //conmap 打印字段实体类
                                        conmap conmap = new conmap();
                                        //根据key,将打印模版的{key}转换成value
                                        conmap.setConKey(key.toString());
                                        conmap.setConValue(value.toString());
                                        conmapList.add(conmap);
                                    });
                                    //将采购订单子表实体转成map，以K,V形式存取，做上面一样的操作
                                    Map purchaseMap = JSON.parseObject(JSON.toJSONString(purchaseItem), Map.class);
                                    System.err.println(purchaseMap);
                                    purchaseMap.forEach((key, value) -> {
                                        System.err.println("4key=" + key + ",value=" + value);
                                        conmap conmap = new conmap();
                                        conmap.setConKey(key.toString());
                                        conmap.setConValue(value.toString());
                                        conmapList.add(conmap);
                                    });
                                    conHead.setConmapList(conmapList);
                                    try {
                                        //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                                        mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);

                                    } catch (Exception e) {

                                    }
                                }
                            });
                        } catch (Exception e) {

                        }

                    } else {
                        return Result.error("没有找到打印模版的数据！请检查！");
                    }
                }
            }

        } else if (StringUtils.isNotBlank(cPid)) {
            //通过cPid，远程调用生产模块，获取制令单BOM信息
            MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(cPid);
            //规格超过50截取50
            if (StringUtils.isNotEmpty(commandbillPitem.getMaterielGauge()) && commandbillPitem.getMaterielGauge().length() > 50) {
                commandbillPitem.setMaterielGauge(commandbillPitem.getMaterielGauge().substring(0, 50));
            }
            BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum());//已发料数量
            BigDecimal batchnum = new BigDecimal(batch);//批次数量
            BigDecimal printPaper = new BigDecimal(printNum);//打印张数
            BigDecimal totalNum = batchnum.multiply(printPaper);//打印总数：打印张次*数量
//			 int totalNum = Integer.valueOf(batch) * printNum;//打印总数：打印张次*数量
            //打印的总数量不能大于未收货数量
            if (totalNum.compareTo(deliveryNum) == 1) {
                return Result.error("打印总数超过未入库数量，请您再次确认！");
            }
            String pid = commandbillPitem.getId(); //制令单Bomid
            String mcode = commandbillPitem.getMaterielCode(); //物料编号
            String mname = commandbillPitem.getMaterielName(); //物料名称
            List<MesStorageWholesale> list = new ArrayList<>();
            //通过物料料号查询物料信息 拿到客户料号
            MesChiefdataMateriel mesChiefdataMateriel = systemClient.queryByMcode(commandbillPitem.getMaterielCode());
            //根据printNum打印次数，进行循环
            for (int i = 0; i < printNum; i++) {
                //批号交易类
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String dateString = formatter.format(new Date());
                MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();
                mesStorageWholesale.setQuery1(dateString);//当前时间
                if (StringUtils.isNotBlank(batchNum)) {
                    mesStorageWholesale.setBatchNum(batchNum);//批次号
                } else {
                    mesStorageWholesale.setBatchNum("  ");//批次号
                }
                if (StringUtils.isNotBlank(clientCode)) {
                    mesStorageWholesale.setClientCode(clientCode);//客户料号
                } else {
                    mesStorageWholesale.setClientCode("  ");//客户料号
                }
                mesStorageWholesale.setBaseCode(pid);//采购订单子表id
                mesStorageWholesale.setBaseDockettype(mobileType);//打印类型
                mesStorageWholesale.setProductCode(mcode);//料号
                mesStorageWholesale.setProductName(mname);//品名
                mesStorageWholesale.setUnit(commandbillPitem.getCountUnit());//单位
                mesStorageWholesale.setWareCode(commandbillPitem.getFactoryCode());//工厂编号
                mesStorageWholesale.setQuery2(commandbillPitem.getFactoryName());//工厂名称
                mesStorageWholesale.setWareSite(commandbillPitem.getStorageSite());//存储位置
                mesStorageWholesale.setInwareNum(batch); //每批的数量
                if (mesChiefdataMateriel!=null&&StringUtils.isNotBlank(mesChiefdataMateriel.getQuery2())){
                    mesStorageWholesale.setClientCode(mesChiefdataMateriel.getQuery2()); //客户料号
                }else {
                    mesStorageWholesale.setClientCode(""); //客户料号
                }

                //每打印一张，就往批号交易表里新增一条数据
                mesStorageWholesaleService.save(mesStorageWholesale);
                list.add(mesStorageWholesale);

                // 获取随机字符串
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                int random = RandomUtils.nextInt(90) + 10;
                String randomNo = format.format(new Date()) + random;

                //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
                MesPrintModel printModel = systemClient.queryByPrintType(mobileType);
                if (printModel != null) {
                    try {
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                //coHead打印的实体类
                                conHead conHead = new conHead();
                                //二维码字段，存放批号交易id
                                conHead.setConBy1(mesStorageWholesale.getId());
                                //随机字符串，用于文件的命名
                                conHead.setOrderNo(randomNo);
                                conHead.setConNo(randomNo);
                                // contempPath：打印模版的url路径，一般是word文档，存在minio里
                                conHead.setContempPath(printModel.getPrintModel());
                                List<conmap> conmapList = new ArrayList<>();//打印字段
                                //将批号交易类实体转成map,以K,V形式存取
                                Map map = JSON.parseObject(JSON.toJSONString(mesStorageWholesale), Map.class);
                                System.err.println(map);
                                //遍历Map，取到Key和Value
                                map.forEach((key, value) -> {
                                    System.err.println("5key=" + key + ",value=" + value);
                                    //conmap 打印字段实体类
                                    conmap conmap = new conmap();
                                    //根据key,将打印模版的{key}转换成value
                                    conmap.setConKey(key.toString());
                                    conmap.setConValue(value.toString());
                                    conmapList.add(conmap);
                                });
                                //将制令单子表实体转成map，以K,V形式存取，做上面一样的操作
                                Map purchaseMap = JSON.parseObject(JSON.toJSONString(commandbillPitem), Map.class);
                                System.err.println(purchaseMap);
                                purchaseMap.forEach((key, value) -> {
                                    System.err.println("6key=" + key + ",value=" + value);
                                    conmap conmap = new conmap();
                                    conmap.setConKey(key.toString());
                                    conmap.setConValue(value.toString());
                                    conmapList.add(conmap);
                                });
                                conHead.setConmapList(conmapList);
                                try {
                                    //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                                    mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);

                                } catch (Exception e) {

                                }
                            }
                        });
                    } catch (Exception e) {

                    }

                } else {
                    return Result.error("没有找到打印模版的数据！请检查！");
                }
            }
        }
        return Result.ok("打印成功");
    }

    /**
     * 扫描入库添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-扫描入库添加")
    @ApiOperation(value = "仓库管理—批号交易-扫描入库添加", notes = "仓库管理—批号交易-扫描入库添加")
    @GetMapping(value = "/scanAdd")
    public Result<?> scanAdd(@RequestParam(name = "id", required = true) String id,
                             @RequestParam(name = "batch", required = true) String batch,
                             @RequestParam(name = "printNum", required = true) int printNum) {
        // 通过id,远程调用业务模块，将采购订单子表数据传过来
        MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(id);
        String pid = purchaseItem.getId(); //采购订单子表id
        String rowNum = purchaseItem.getRowNum(); //行号
        String mcode = purchaseItem.getMaterielCode();  //物料编号
        String mname = purchaseItem.getMaterielName(); //物料名称
        String unit = purchaseItem.getOrderUnit(); //单位
        String type = "入库打印";
        List<MesStorageWholesale> list = new ArrayList<>();
        for (int i = 0; i < printNum; i++) {
            MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();
            mesStorageWholesale.setBaseRownum(rowNum);
            mesStorageWholesale.setBaseCode(pid);
            mesStorageWholesale.setBaseDockettype(type);
            mesStorageWholesale.setProductCode(mcode);
            mesStorageWholesale.setProductName(mname);
            mesStorageWholesale.setInwareNum(batch);
            mesStorageWholesale.setUnit(unit);
            mesStorageWholesaleService.save(mesStorageWholesale);
            list.add(mesStorageWholesale);
        }
        return Result.ok(list);
    }

    /**
     * 编辑
     *
     * @param mesStorageWholesale
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-编辑")
    @ApiOperation(value = "仓库管理—批号交易-编辑", notes = "仓库管理—批号交易-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesStorageWholesale mesStorageWholesale) {
        mesStorageWholesaleService.updateById(mesStorageWholesale);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-通过id删除")
    @ApiOperation(value = "仓库管理—批号交易-通过id删除", notes = "仓库管理—批号交易-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesStorageWholesaleService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-批量删除")
    @ApiOperation(value = "仓库管理—批号交易-批量删除", notes = "仓库管理—批号交易-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesStorageWholesaleService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-通过id查询")
    @ApiOperation(value = "仓库管理—批号交易-通过id查询", notes = "仓库管理—批号交易-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id,
                               @RequestParam(name = "type", required = false) String type) {
        MesStorageWholesale mesStorageWholesale = mesStorageWholesaleService.getById(id);

        if (mesStorageWholesale == null) {
            //this.recordErrorOperation("/storage/mesStorageWholesale/queryById","制令单上料","仓库管理—批号交易-通过id查询","未找到对应数据", mesStorageWholesale);
            return Result.error("未找到对应数据");
        }
        if ("上料".equals(type)) {
            String productName = mesStorageWholesale.getProductName();
            if (StringUtils.isNotEmpty(productName)&&productName.contains("锡膏")) {
                MesAncillarytoolStir mesAncillarytoolStir = produceClient.queryAncillaryBySn(mesStorageWholesale.getId());
                if (mesAncillarytoolStir == null) {
                    //this.recordErrorOperation("/storage/mesStorageWholesale/queryById","制令单上料","仓库管理—批号交易-通过id查询","锡膏搅拌没有达标，无法上料！", mesStorageWholesale);
                    Result.error("锡膏搅拌没有达标，无法上料！");
                }
            }
        }
        return Result.ok(mesStorageWholesale);
    }
    /**
     * 通过id查询追踪记录
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-通过id查询追踪记录")
    @ApiOperation(value = "仓库管理—批号交易-通过id查询追踪记录", notes = "仓库管理—批号交易-通过id查询追踪记录")
    @GetMapping(value = "/findByIdTraceBack")
    public Result<?> findByIdTraceBack(@RequestParam(name = "id") String id) {
        List<MesStorageWholesale> mesStorageWholesales = mesStorageWholesaleService.findByIdTraceBack(id);
        return Result.ok(mesStorageWholesales);
    }
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理—批号交易-通过id查询")
    @ApiOperation(value = "仓库管理—批号交易-通过id查询", notes = "仓库管理—批号交易-通过id查询")
    @GetMapping(value = "/findById")
    public MesStorageWholesale findById(@RequestParam(name = "id") String id) {
        MesStorageWholesale mesStorageWholesale = mesStorageWholesaleService.getById(id);
        return mesStorageWholesale;
    }

    @AutoLog(value = "仓库管理—批号交易-通过baseCode（制令单bom id）和 扫描上料 查询")
    @ApiOperation(value = "仓库管理—批号交易-通过baseCode（制令单bom id）和 扫描上料 查询", notes = "仓库管理—批号交易-通过baseCode（制令单bom id）和 扫描上料 查询")
    @GetMapping(value = "/findbaseCode")
    public List<MesStorageWholesale> baseCodefind(@RequestParam(name = "baseCode") String baseCode) {
        QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("base_dockettype", "扫描上料");
        queryWrapper.eq("base_code", baseCode);
        return mesStorageWholesaleService.list(queryWrapper);
    }

    /**
     * 根据制令单id查询制令单上料信息，用于验证上料数量 远程调用
     *
     * @param query4
     * @return
     */
    @GetMapping(value = "/selectQuery4SL")
    public List<MesStorageWholesale> selectQuery4SL(@RequestParam(name = "query4") String query4) {
        return mesStorageWholesaleService.selectQuery4SL(query4);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesStorageWholesale
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesStorageWholesale mesStorageWholesale) {
        return super.exportXls(request, mesStorageWholesale, MesStorageWholesale.class, "仓库管理—批号交易");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesStorageWholesale.class);
    }

    /**
     * 拆分板-根据批号ID查询拆分板
     */
    @AutoLog(value = "根据批号ID查询拆分板")
    @ApiOperation(value = "拆分板-根据批号ID查询拆分板", notes = "拆分板-根据批号ID查询拆分板")
    @GetMapping(value = "/findSplitBoard")
    public Result<?> findSplitBoard(@RequestParam(name = "id") String id) {
        return mesStorageWholesaleService.findSplitBoard(id);
    }

    /**
     * 拆分板-打印
     *
     * @param id         必传 制令单ID、批号交易ID
     * @param mobileType 非必传  打印类型 不传默认：拆板打印
     * @param printNum   必传 打印张数
     */
    @AutoLog(value = "拆分板-打印")
    @ApiOperation(value = "拆分板-打印", notes = "拆分板-打印")
    @GetMapping(value = "/splitBoard")
    public Result<?> splitBoard(@RequestParam(name = "id") String id,
                                @RequestParam(name = "mobileType", required = false) String mobileType,
                                @RequestParam(name = "printNum") int printNum) {
        log.info("拆分板-打印入参:splitBoard>>id>" + id + ">>mobileType>" + mobileType + ">>printNum>" + printNum);
        if (printNum > 10) {
            return Result.error("一次打印张数，最多可打印10张！");
        }
        MesCommandbillInfo commandBillInfo;
        MesStorageWholesale wholesale = null;
        boolean flag = false;
        if (StringUtils.isNotBlank(id)) {
            commandBillInfo = produceClient.getById(id);
            log.info("拆分板-打印:splitBoard>>commandBillInfo>" + JSON.toJSONString(commandBillInfo));
            if (com.epms.util.ObjectHelper.isEmpty(commandBillInfo)) {
                wholesale = mesStorageWholesaleService.getById(id);
                flag = true;
                log.info("拆分板-打印:splitBoard>>wholesale>" + JSON.toJSONString(wholesale));
            }
        } else {
            return Result.error("扫描失败，未获取到ID请检查！");
        }
        if (StringUtils.isBlank(mobileType)) {
            mobileType = "拆板打印";
        }
        //根据printNum打印次数，进行循环
        for (int i = 0; i < printNum; i++) {
            MesStorageWholesale mesStorageWholesale;
            if (com.epms.util.ObjectHelper.isNotEmpty(commandBillInfo)) {
                mesStorageWholesale = new MesStorageWholesale();
                mesStorageWholesale = insertMesCommandBillInfo(mesStorageWholesale, commandBillInfo, mobileType);
            } else {
                if (com.epms.util.ObjectHelper.isNotEmpty(wholesale)) {
                    //if ("制令单线程扫描".equals(wholesale.getBaseDockettype())) {
                    mesStorageWholesale = new MesStorageWholesale();
                    mesStorageWholesale = insertMesStorageWholesale(mesStorageWholesale, wholesale, mobileType, null);
                    //}
                } else {
                    return Result.error("数据查询失败，请检查ID是否正确！");
                }
            }
            /*if (com.epms.util.ObjectHelper.isEmpty(mesStorageWholesale)) {
                mesStorageWholesale = new MesStorageWholesale();
                mesStorageWholesale = initMesStorageWholesale(mesStorageWholesale, mobileType);
            }*/
            //String jsonStr = JSON.toJSONString(mesStorageWholesale);
            synchronized (this) {
                String printResult = this.printLabel(null, mesStorageWholesale.getId(), mobileType);
                if (!"ok".equals(printResult)) {
                    return Result.error(printResult);
                }
            }
        }
        if (flag) {
            if (!"isSplitBoard".equals(wholesale.getQuery4())) {
                wholesale.setQuery4("isSplitBoard");//设置拆分板状态
                mesStorageWholesaleService.updateById(wholesale);
            }
            /*if (StringUtils.isNotBlank(wholesale.getInwareNum()) && this.checkInWareNum(wholesale.getInwareNum(),printNum)) {
                wholesale.setInwareNum(new BigDecimal(wholesale.getInwareNum()).subtract(new BigDecimal(printNum)).toString());
                mesStorageWholesaleService.updateById(wholesale);
            }else{
                return Result.ok("注意：打印数量大于入库数量，请查看是否有问题在操作！");
            }*/
        }
        return Result.ok("拆分板打印成功！");
    }

    /**
     * 盘点入库-根据批号ID查询物料入库
     * 说明：扫描二维码查询批号交易记录进行入库
     * 如果通过物料编号查询到库存，将批号交易的入库数量添加到该库存
     * 如果通过物料编号未查到库存，新建一条入库记录，将批号交易的入库数量和其他可用信息写入该记录
     */
    @AutoLog(value = "根据批号ID查询物料入库")
    @ApiOperation(value = "盘点入库-根据批号ID查询物料入库", notes = "盘点入库-根据批号ID查询物料入库")
    @GetMapping(value = "/checkStockInById")
    public Result<?> checkStockInById(@RequestParam(name = "id") String id) {
        return mesStorageWholesaleService.checkStockInById(id);
    }

    /**
     * 盘点库存-打印
     *
     * @param id         必传 批号交易ID
     * @param number     必传 打印张数
     * @param printNum   必传 打印张数
     * @param mobileType 非必传  打印类型 不传默认：拆板打印
     */
    @AutoLog(value = "盘点库存-打印")
    @ApiOperation(value = "盘点库存-打印", notes = "盘点库存-打印(number/printNum:必传  id/mobileType:非必传)")
    @GetMapping(value = "/inventoryPrinting")
    public Result<?> inventoryPrinting(@RequestParam(name = "id") String id,
                                       @RequestParam(name = "number") String number,
                                       @RequestParam(name = "printNum") int printNum,
                                       @RequestParam(name = "mobileType", required = false) String mobileType) {
        log.info("盘点库存-打印入参:inventoryPrinting>>id>" + id + ">>mobileType>" + mobileType + ">>number>" + number + ">>printNum>" + printNum);
        if (printNum > 10) {
            return Result.error("一次打印张数，最多可打印10张！");
        }
        MesStorageWholesale wholesale = mesStorageWholesaleService.getById(id);
        log.info("盘点库存-打印:inventoryPrinting>>wholesale>" + JSON.toJSONString(wholesale));
        if (com.epms.util.ObjectHelper.isEmpty(wholesale)) {
            return Result.error("未查到该物料的批号交易，请检查！");
        }
        if (StringUtils.isBlank(mobileType)) {
            mobileType = "盘点打印";
        }
        //根据printNum打印次数，进行循环
        for (int i = 0; i < printNum; i++) {
            MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();
            mesStorageWholesale = insertMesStorageWholesale(mesStorageWholesale, wholesale, mobileType, number);
            String jsonStr = JSON.toJSONString(mesStorageWholesale);
            synchronized (this) {
                String printResult = this.printLabel(jsonStr, mesStorageWholesale.getId(), mobileType);
                if (!"ok".equals(printResult)) {
                    return Result.error(printResult);
                }
            }
        }
        return Result.ok("盘点库存打印成功！");
    }

    /**
     * 初始化批号交易
     */
    private MesStorageWholesale initMesStorageWholesale(MesStorageWholesale mesStorageWholesale, String mobileType) {
        log.info("初始化批号交易入参:initMesStorageWholesale>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale) + ">>mobileType>" + mobileType);
        //批号交易类
        mesStorageWholesale.setBaseDockettype("初始化_" + mobileType);//打印类型
        mesStorageWholesale.setInwareNum("1"); //每批的数量
        //每打印一张，就往批号交易表里新增一条数据
        mesStorageWholesaleService.save(mesStorageWholesale);
        log.info("初始化批号交易出参:initMesStorageWholesale>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        return mesStorageWholesale;
    }

    /**
     * 从制令单导入记录
     */
    private MesStorageWholesale insertMesCommandBillInfo(MesStorageWholesale mesStorageWholesale, MesCommandbillInfo commandBillInfo, String mobileType) {
        log.info("从制令单导入记录入参:insertMesCommandBillInfo>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale) + ">>commandBillInfo>" + JSON.toJSONString(commandBillInfo) + ">>mobileType>" + mobileType);
        //批号交易类
        mesStorageWholesale.setQuery5(commandBillInfo.getId());//主数据关联
        mesStorageWholesale.setQuery1(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(DateUtils.getDate()));//当前时间
        mesStorageWholesale.setBaseCode(commandBillInfo.getId());//制令单id
        mesStorageWholesale.setBaseDockettype("制令单_" + mobileType);//打印类型
        mesStorageWholesale.setProductCode(commandBillInfo.getMechanismCode());//料号
        mesStorageWholesale.setProductName(commandBillInfo.getMechanismName());//品名
        mesStorageWholesale.setInwareNum("1"); //每批的数量
        if (StringUtils.isNotBlank(commandBillInfo.getProduceId())) {
            mesStorageWholesale.setBaseRownum(commandBillInfo.getProduceId()); //生产订单ID
            MesOrderProduce produce = transactionClient.queryMesProduceById(commandBillInfo.getProduceId());
            if (produce != null) {
                mesStorageWholesale.setUnit(produce.getUnit());//单位
                mesStorageWholesale.setWareCode(produce.getFactoryCode());//工厂编号
                mesStorageWholesale.setQuery2(produce.getFactoryName());//工厂名称
                mesStorageWholesale.setWareSite(produce.getStorageSite());//存储位置
            }
        }
        //每打印一张，就往批号交易表里新增一条数据
        mesStorageWholesaleService.save(mesStorageWholesale);
        log.info("从制令单导入记录出参:insertMesCommandBillInfo>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        return mesStorageWholesale;
    }

    /**
     * 从批号交易导入记录
     */
    private MesStorageWholesale insertMesStorageWholesale(MesStorageWholesale mesStorageWholesale, MesStorageWholesale wholesale, String mobileType, String number) {
        log.info("从批号交易导入记录入参:insertMesStorageWholesale>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale) + ">>wholesale>" + JSON.toJSONString(wholesale) + ">>mobileType>" + mobileType + ">>number>" + number);
        //批号交易类
        mesStorageWholesale.setQuery5(wholesale.getId());//主数据关联
        mesStorageWholesale.setQuery1(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(DateUtils.getDate()));//当前时间
        mesStorageWholesale.setBaseCode(wholesale.getBaseCode());//采购订单子表id
        mesStorageWholesale.setBaseDockettype("批号交易_" + mobileType);//打印类型
        if (ObjectHelper.isNotEmpty(wholesale.getProductCode())) {
            MesChiefdataMateriel mesChiefdataMateriel = systemClient.queryByMcode(wholesale.getProductCode());
            if (ObjectHelper.isNotEmpty(mesChiefdataMateriel)) {
                mesStorageWholesale.setGauge(mesChiefdataMateriel.getGauge());//规格
            }else{
                mesStorageWholesale.setGauge(" ");//规格
            }
        }
        //规格超过50截取50
        if (StringUtils.isNotEmpty(mesStorageWholesale.getGauge()) && mesStorageWholesale.getGauge().length() > 50) {
            mesStorageWholesale.setGauge(mesStorageWholesale.getGauge().substring(0, 50));
        }
        mesStorageWholesale.setProductCode(wholesale.getProductCode());//料号
        mesStorageWholesale.setProductName(wholesale.getProductName());//品名
        mesStorageWholesale.setUnit(wholesale.getUnit());//单位
        mesStorageWholesale.setWareCode(wholesale.getWareCode());//工厂编号
        mesStorageWholesale.setQuery2(wholesale.getQuery2());//工厂名称
        mesStorageWholesale.setWareSite(wholesale.getWareSite());//存储位置
        mesStorageWholesale.setInwareNum(StringUtils.isBlank(number) ? "1" : number); //每批的数量
        mesStorageWholesale.setRowNum(wholesale.getRowNum());//行号
        mesStorageWholesale.setBaseRownum(wholesale.getBaseRownum());//基本行号
        mesStorageWholesale.setOutwareNum(wholesale.getOutwareNum());//出库数量
        mesStorageWholesale.setQuery3(wholesale.getQuery3());//凭证抬头id
        mesStorageWholesale.setBatchNum(wholesale.getBatchNum());//批次号
        mesStorageWholesale.setClientCode(wholesale.getClientCode());//客户料号
        mesStorageWholesale.setGlazeId(wholesale.getGlazeId());//上料id
        mesStorageWholesale.setShelfCode(wholesale.getShelfCode());//货架编码
        mesStorageWholesale.setShelfState(wholesale.getShelfState());//货架状态
        mesStorageWholesale.setAreaCode(wholesale.getAreaCode());//区域编码
        mesStorageWholesale.setLocationCode(wholesale.getLocationCode());//位置编码
        //每打印一张，就往批号交易表里新增一条数据
        mesStorageWholesaleService.save(mesStorageWholesale);
        log.info("从批号交易导入记录出参:insertMesStorageWholesale>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        return mesStorageWholesale;
    }

    /**
     * 打印
     *
     * @param jsonStr
     * @param id
     * @param mobileType
     * @return
     */
    private String printLabel(String jsonStr, String id, String mobileType) {
        log.info("打印入参:printLabel>>jsonStr>" + jsonStr + ">>id>" + id + ">>mobileType>" + mobileType);
        //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
        MesPrintModel printModel = systemClient.queryByPrintType(mobileType);
        log.info("打印:printLabel>>printModel>" + JSON.toJSONString(printModel));
        if (printModel != null) {
            try {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        //coHead打印的实体类
                        conHead conHead = new conHead();
                        //二维码字段，存放批号交易id
                        conHead.setConBy1(id);
                        // 获取随机字符串
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                        int random = RandomUtils.nextInt(90) + 10;
                        String randomNo = format.format(new Date()) + random;
                        //随机字符串，用于文件的命名
                        conHead.setOrderNo(randomNo);
                        conHead.setConNo(randomNo);
                        // contempPath：打印模版的url路径，一般是word文档，存在minio里
                        conHead.setContempPath(printModel.getPrintModel());
                        if (StringUtils.isNotBlank(jsonStr)) {
                            List<conmap> conmapList = new ArrayList<>();//打印字段
                            //将批号交易类实体转成map,以K,V形式存取
                            Map map = JSON.parseObject(jsonStr, Map.class);
                            System.err.println(map);
                            //遍历Map，取到Key和Value
                            map.forEach((key, value) -> {
                                System.err.println("7key=" + key + ",value=" + value);
                                //conmap 打印字段实体类
                                conmap conmap = new conmap();
                                //根据key,将打印模版的{key}转换成value
                                conmap.setConKey(key.toString());
                                conmap.setConValue(value.toString());
                                conmapList.add(conmap);
                            });
                            conHead.setConmapList(conmapList);
                        }
                        //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                        log.info("打印:printLabel>>conHead>" + JSON.toJSONString(conHead));
                        mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);
                    }
                });
            } catch (Exception e) {
                return "网络不稳定，请稍后在试！";
            }
            return "ok";
        } else {
            return "没有找到打印模版的数据！请检查！";
        }
    }

    /**
     * 记录错误操作
     */
    private void recordErrorOperation(String callAddress, String operationSteps, String wrongSteps, String errMeg, String commandBillId) {
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MesErrorOperationRecord errorOperationRecord = new MesErrorOperationRecord();
        errorOperationRecord.setCreateBy(sysUser.getRealname());//创建人
        //errorOperationRecord.setCreateTime(new Date);//创建日期
        errorOperationRecord.setSysOrgCode(sysUser.getOrgCode());//所属部门
        errorOperationRecord.setOperatorId(sysUser.getId());//操作人ID
        errorOperationRecord.setOperatorAccount(sysUser.getUsername());//操作人账号
        errorOperationRecord.setPhone(sysUser.getPhone());//操作人电话
        //errorOperationRecord.setUserStatus(sysUser.getStatus());//用户状态

        errorOperationRecord.setCallAddress(callAddress);//调用地址
        errorOperationRecord.setOperationSteps(operationSteps);//操作步骤
        errorOperationRecord.setWrongSteps(wrongSteps);//错误步骤
        errorOperationRecord.setErrorCause(errMeg);//错误原因
        if (StringUtils.isNotBlank(commandBillId)) {
            MesCommandbillInfo mesCommandBillInfo = produceClient.getById(commandBillId);
            if (com.epms.util.ObjectHelper.isNotEmpty(mesCommandBillInfo)) {
                errorOperationRecord.setLineType(mesCommandBillInfo.getLineType());//线别
                errorOperationRecord.setProduceGrade(mesCommandBillInfo.getProduceGrade());//阶别
            }
        }
        //errorOperationRecord.setRemark();//备注
        iMesErrorOperationRecordService.add(errorOperationRecord);
    }

    /**
     * 检查入库数量是否大于打印数量
     */
    private boolean checkInWareNum(String inWareNum, int printNum) {
        if (new BigDecimal(inWareNum).compareTo(new BigDecimal(printNum)) == -1) {
            return false;
        }
        return true;
    }

    /**
     * 获取扫描上料记录 根据旧料盘id查询
     */
    @AutoLog(value = "获取扫描上料记录 根据旧料盘id查询")
    @ApiOperation(value = "获取扫描上料记录 根据旧料盘id查询", notes = "获取扫描上料记录 根据旧料盘id查询")
    @GetMapping(value = "/getshangliao")
    public  Result<?> getshangliao(String id){
        List<MesStorageWholesale> getshangliao = mesStorageWholesaleService.getshangliao(id);
        if(getshangliao==null||getshangliao.size()==0){
            return Result.error("未找到该上料信息！");
        }
        return Result.ok(getshangliao);
    }
}
